package com.chat.common.common.interceptor;

import com.chat.common.common.exception.HttpErrorEnum;
import com.chat.common.user.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;
@Order(-2)
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final String AUTHORIZATION = "Authorization";
    public static final String BEARER_ = "Bearer ";
    public static final String UID = "uid";

    @Resource
    private LoginService loginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getAuthorizeToken(request);
        Long validUid = loginService.getValidUid(token);
        if(Objects.nonNull(validUid)) {
            request.setAttribute(UID,validUid);
        }else {
            //用户登录 失效 判断 该接口是否为公开接口
            boolean IsPublicUri = isPublicUri(request);
            if(!IsPublicUri) {
                //返回401
                HttpErrorEnum.ACCESS_DENIED.sendHttpError(response);
                return false;
            }
        }
        return true;
    }

    private static boolean isPublicUri(HttpServletRequest request) {
        String requestURL = request.getRequestURI();
        String[] split = requestURL.split("/");
        return split.length>3&&"public".equals(split[3]);
    }


    private String getAuthorizeToken(HttpServletRequest request) {
        String authorize = request.getHeader(AUTHORIZATION);
        return Optional.ofNullable(authorize)
                .filter(a -> a.startsWith(BEARER_))
                .map(a -> a.substring(BEARER_.length()))
                .orElse(null);

    }
}
